package com.goldenautumn.prefabricate.activity.mine.address

import android.view.View
import android.view.animation.AnimationUtils
import android.widget.EditText
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.VibrateUtils
import com.github.gzuliyujiang.wheelpicker.AddressPicker
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode
import com.github.gzuliyujiang.wheelpicker.contract.OnAddressPickedListener
import com.github.gzuliyujiang.wheelpicker.contract.OnLinkageSelectedListener
import com.github.gzuliyujiang.wheelpicker.entity.CityEntity
import com.github.gzuliyujiang.wheelpicker.entity.CountyEntity
import com.github.gzuliyujiang.wheelpicker.entity.ProvinceEntity
import com.github.gzuliyujiang.wheelpicker.utility.AddressJsonParser
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.business.entity.AddressCreateParams
import com.goldenautumn.prefabricate.business.entity.AddressInfoVo
import com.goldenautumn.prefabricate.business.entity.OrderMenuInfoVo
import com.goldenautumn.prefabricate.business.user.UserAddressUiState
import com.goldenautumn.prefabricate.business.user.UserInfoUiState
import com.goldenautumn.prefabricate.business.user.UserViewModel
import com.goldenautumn.prefabricate.databinding.ActivityAddressEditBinding
import com.goldenautumn.prefabricate.utils.Constants
import com.goldenautumn.prefabricate.utils.Constants.BUSINESS_PAGE_DATA
import com.goldenautumn.prefabricate.utils.loadImgUrl
import com.goldenautumn.prefabricate.utils.onCenterToast
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select
import qncx.external.common.base.BaseActivity
import qncx.external.common.compat.getIntentSerializable
import qncx.external.common.compat.gone
import qncx.external.common.compat.visible
import qncx.external.common.widget.dialog.PromptDialog
import qncx.external.common.widget.shapeview.shape.ShapeLinearLayout

class AddressEditActivity : BaseActivity<ActivityAddressEditBinding>(), OnAddressPickedListener {

    private var provinceEntity:List<ProvinceEntity>? = null

    private val mUserModel by viewModels<UserViewModel>()

    var params = AddressCreateParams()

    private val addressInfo: AddressInfoVo?
        get() = getIntentSerializable(intent, BUSINESS_PAGE_DATA,AddressInfoVo::class.java)

    override fun getLayoutId(): Int = R.layout.activity_address_edit

    override suspend fun main() {
        mBinding.title.setText(if(addressInfo == null) R.string.new_address else R.string.edit_address)
        ImmersionBar.setTitleBar(this, mBinding.toolbar)
        initToolbarNav(mBinding.toolbar)

        mBinding.name.OnFocusStatus(mBinding.nameLine)

        mBinding.address.OnFocusStatus(mBinding.addressLine)

//        mBinding.postal.OnFocusStatus(mBinding.postalLine)

        mBinding.phone.OnFocusStatus(mBinding.phoneLine)

        mBinding.saveBtn.setOnClickListener {

            mBinding.name.InputRegex(mBinding.nameLine,mBinding.nameWarn)

            mBinding.address.InputRegex(mBinding.addressLine,mBinding.addressWarn)

//            mBinding.postal.InputRegex(mBinding.postalLine,mBinding.postalWarn)

            mBinding.phone.InputRegex(mBinding.phoneLine,mBinding.phoneWarn)

            params.address_id = if(addressInfo == null) null else addressInfo?.address_id
            params.name = mBinding.name.text?.trim().toString()
            params.phone = mBinding.phone.text?.trim().toString()
            params.region = mBinding.provinces.text?.trim().toString()
            params.detail = mBinding.address.text?.trim().toString()
            params.is_default = if(mBinding.switchBtn.switchIsChecked) 1 else 0

            if(!mBinding.nameWarn.isVisible && !mBinding.addressWarn.isVisible && !mBinding.phoneWarn.isVisible && params.region != null) {
                if(params.address_id != null) mUserModel.onUpdateAddress(params)
                else mUserModel.onCreateAddress(params)
            } else {
                VibrateUtils.vibrate(50)
                mBinding.saveBtn.startAnimation(AnimationUtils.loadAnimation(this, R.anim.shake_anim))
            }

        }

        addressInfo?.let {
            mBinding.name.setText("${it?.name}")
            mBinding.phone.setText("${it?.phone}")
            mBinding.provinces.text = "${it?.region?.province},${it?.region?.city},${it?.region?.region}"
            mBinding.address.setText("${it?.detail}")
            mBinding.switchBtn.switchIsChecked = it?.isDefault == true
        }

        mUserModel.getRegionTree()

        mBinding.provinces.setOnClickListener {
            var oldCity = mBinding.provinces.text.toString()
            var arr:List<String> = ArrayList()
            if(oldCity.contains(",")) arr = oldCity.split(",")
            val picker = AddressPicker(this)
            picker.setAddressLoader(TextAddressLoader(provinceEntity),  TextAddressParser())
            if(arr.size == 3) picker.setDefaultValue(arr[0], arr[1], arr[2])
            picker.setOnAddressPickedListener(this)
            picker.wheelLayout.setOnLinkageSelectedListener { first, second, third ->
                picker.titleView.text = String.format(
                    "%s%s%s",
                    picker.firstWheelView.formatItem(first),
                    picker.secondWheelView.formatItem(second),
                    picker.thirdWheelView.formatItem(third)
                )
            }
            picker.show()
        }

        while (isActive) {
            select {
                mUserModel.addressUiState.onReceive {
                    when(it) {
                        is UserAddressUiState.AddressTree -> {
                            provinceEntity = it.tree
                        }
                        is UserAddressUiState.AddressAction -> {
                            if(!it.isSuccess) onCenterToast("${it.msg}")
                            else PromptDialog().setConfirmListener(object :PromptDialog.ConfirmHandleListener {
                                override fun bindView(dialog: PromptDialog, view: PromptDialog.PromptModel) {
                                    dialog.setCanTouchCancel(false)
                                    view.setMsgText(getString(R.string.operation_success))
                                    view.getPromptConfirm().setOnClickListener {
                                        dialog.dismiss()
                                        setResult(RESULT_OK)
                                        onBackPressedDispatcher.onBackPressed()
                                    }
                                }
                            }).onShow(supportFragmentManager.beginTransaction())
                        }
                        else -> {}
                    }
                }
            }
        }

    }

    fun View.OnFocusStatus(line:ShapeLinearLayout) {
        setOnFocusChangeListener { view, hasFocus ->
            line.shapeBuilder
                ?.setShapeStrokeColor(ContextCompat.getColor(view.context,if(hasFocus) R.color.colorPrimary else qncx.external.common.R.color.color_cccccc))
                ?.into(line)
        }
    }

    fun EditText.InputRegex(line:ShapeLinearLayout,warnView:TextView? = null){
        var content = text.trim().toString()
        if(content.isEmpty()) {
            warnView?.visible()
            line.shapeBuilder
                ?.setShapeStrokeColor(ContextCompat.getColor(line.context,R.color.color_DE0000))
                ?.into(line)
        } else {
            warnView?.gone()
            line.shapeBuilder
                ?.setShapeStrokeColor(ContextCompat.getColor(line.context, qncx.external.common.R.color.color_cccccc))
                ?.into(line)
        }
    }

    override fun onAddressPicked(province: ProvinceEntity?, city: CityEntity?, county: CountyEntity?) {
        mBinding.provinces.text = "${province?.name},${city?.name},${county?.name}"
    }

}